<template>
	<view class="footprint-list">
		<!-- 导航栏 -->
		<nav-bar backUrl="/pages/my/my" :isTabbar="true"></nav-bar>
		<!-- 清空按钮 -->
		<view class="clear-btn" @tap="clearFootprints">
			<text>清空浏览记录</text>
		</view>
		<!-- 日期分组列表 -->
		<view class="date-groups">
			<view class="date-group" v-for="(group, index) in footprints" :key="index">
				<!-- 日期标题 -->
				<view class="date-header">
					<text class="date">{{ group.date }}</text>
					<text class="tag" v-if="group.tag">{{ group.tag }}</text>
				</view>
				
				<!-- 服务记录列表 -->
				<view class="service-list">
					<view class="service-item" 
						v-for="(service, sIndex) in group.services" 
						:key="sIndex"
						@tap="viewServiceDetail(service)"
					>
						<view class="service-image">
							<image :src="service.image" mode="aspectFill"></image>
						</view>
						<view class="service-content">
							<view class="service-title">{{ service.title }}</view>
							<view class="service-desc">{{ service.description }}</view>
							<view class="service-code">{{ service.code }}</view>
							<view class="service-code">{{ service.visitTime }}</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue'
export default {
	components: {
		NavBar
	},
	data() {
		return {
			footprints: []
		}
	},

	onLoad() {
		this.loadFootprints()
	},

	methods: {
		goBack() {
			uni.navigateBack()
		},
		
		viewServiceDetail(service) {
			uni.navigateTo({
				url: `/pages/service-detail/service-detail?id=${service.projectId}`
			})
		},

		// 清空浏览记录
		async clearFootprints() {
			try {
				const userInfoStr = uni.getStorageSync('userInfo')
				let userInfo = null
				
				if (userInfoStr) {
					try {
						if (typeof userInfoStr === 'string') {
							const parsed = JSON.parse(userInfoStr)
							if (parsed.code === 200 && parsed.data) {
								userInfo = parsed.data
							} else {
								userInfo = parsed
							}
						} else {
							userInfo = userInfoStr
						}
					} catch (e) {
						console.error('解析用户信息失败', e)
						userInfo = userInfoStr
					}
				}

				// 显示确认对话框
				uni.showModal({
					title: '提示',
					content: '确定要清空所有浏览记录吗？',
					success: async (res) => {
						if (res.confirm) {
							const result = await uni.request({
								url: `${uni.$config.baseUrl}/footprint/clear/${userInfo.memberId}`,
								method: 'DELETE'
							})

							if (result.data.code === 200) {
								uni.showToast({
									title: '清空成功',
									icon: 'success'
								})
								// 重新加载列表
								this.loadFootprints()
							} else {
								uni.showToast({
									title: result.data.msg || '清空失败',
									icon: 'none'
								})
							}
						}
					}
				})
			} catch (error) {
				console.error('清空足迹失败:', error)
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				})
			}
		},

		// 加载足迹列表
		async loadFootprints() {
			try {
				const userInfoStr = uni.getStorageSync('userInfo')
				let userInfo = null
				
				if (userInfoStr) {
				  try {
				    // 如果是字符串，尝试解析
				    if (typeof userInfoStr === 'string') {
				      const parsed = JSON.parse(userInfoStr)
				      // 检查是否是登录响应格式
				      if (parsed.code === 200 && parsed.data) {
				        userInfo = parsed.data
				      } else {
				        userInfo = parsed
				      }
				    } else {
				      // 如果不是字符串，直接使用
				      userInfo = userInfoStr
				    }
				  } catch (e) {
				    console.error('解析用户信息失败', e)
				    // 解析失败时，尝试直接使用
				    userInfo = userInfoStr
				  }
				}

				const res = await uni.request({
					url: `${uni.$config.baseUrl}/footprint/list/${userInfo.memberId}`,
					method: 'GET'
				})

				if (res.data.code === 200) {
					// 对数据按日期分组处理
					const groupedData = this.groupFootprintsByDate(res.data.data)
					this.footprints = groupedData
				} else {
					uni.showToast({
						title: res.data.msg || '获取足迹失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('加载足迹失败:', error)
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				})
			}
		},

		// 按日期分组处理足迹数据
		groupFootprintsByDate(list) {
			if (!list || list.length === 0) return []

			// 使用 Map 按日期分组
			const groupMap = new Map()
			
			list.forEach(item => {
				// 将时间戳转换为日期字符串 YYYY年MM月DD日
				const date = new Date(item.visitTime)
				const dateStr = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
				
				if (!groupMap.has(dateStr)) {
					groupMap.set(dateStr, {
						date: dateStr,
						services: []
					})
				}
				
				// 构造服务对象
				const service = {
					projectId: item.projectId,
					title: item.projectName,
					description: item.projectDesc,
					visitTime: item.visitTime,
					image: item.projectImage
				}
				
				groupMap.get(dateStr).services.push(service)
			})
			
			// 转换为数组并按日期倒序排序
			return Array.from(groupMap.values()).sort((a, b) => {
				return new Date(b.date.replace(/[年月日]/g, '/')) - new Date(a.date.replace(/[年月日]/g, '/'))
			})
		}
	}
}
</script>

<style lang="scss">
.footprint-list {
	min-height: 100vh;
	background: #F8F8F8;
	
	.clear-btn {
		margin: 20rpx;
		padding: 20rpx;
		background: #FFFFFF;
		border-radius: 8rpx;
		text-align: center;
		color: #FF4D4F;
		font-size: 28rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		
		&:active {
			opacity: 0.8;
		}
	}
	
	.nav-header {
		background: #FFFFFF;
		padding: 20rpx 30rpx;
		display: flex;
		align-items: center;
		border-bottom: 1rpx solid #EEEEEE;
		
		.back-icon {
			font-size: 28rpx;
			color: #333;
			padding: 10rpx 20rpx;
		}
		
		.title {
			flex: 1;
			text-align: center;
			font-size: 32rpx;
			color: #333;
			font-weight: 500;
			margin-right: 60rpx; // 为了保持标题居中
		}
	}
	
	.date-groups {
		padding: 20rpx;
		
		.date-group {
			margin-bottom: 30rpx;
			
			.date-header {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;
				
				.date {
					font-size: 32rpx;
					color: #333;
					font-weight: bold;
				}
				
				.tag {
					margin-left: 20rpx;
					font-size: 24rpx;
					color: #666;
					padding: 4rpx 12rpx;
					background: #F0F0F0;
					border-radius: 4rpx;
				}
			}
			
			.service-list {
				display: grid;
				grid-template-columns: repeat(3, 1fr);
				gap: 20rpx;
				
				.service-item {
					background: #FFFFFF;
					border-radius: 12rpx;
					overflow: hidden;
					box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
					
					.service-image {
						width: 100%;
						height: 200rpx;
						
						image {
							width: 100%;
							height: 100%;
							object-fit: cover;
						}
					}
					
					.service-content {
						padding: 16rpx;
						
						.service-title {
							font-size: 28rpx;
							color: #333;
							font-weight: 500;
							margin-bottom: 8rpx;
						}
						
						.service-desc {
							font-size: 24rpx;
							color: #666;
							line-height: 1.4;
							margin-bottom: 8rpx;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2;
							overflow: hidden;
						}
						
						.service-code {
							font-size: 24rpx;
							color: #999;
						}
					}
					
					&:active {
						opacity: 0.9;
					}
				}
			}
		}
	}
}
</style> 